﻿using DotNetty.Codecs.Http.WebSockets;
using DotNetty.Handlers.Timeout;
using DotNetty.Transport.Channels;

namespace DotNetty.Extensions
{
    class WebSocketClientHandler : SimpleChannelInboundHandler<WebSocketFrame>
    {
        private readonly WebSocketClient _client;

        public WebSocketClientHandler(WebSocketClient client)
        {
            _client = client;
        }

        //public override void ChannelActive(IChannelHandlerContext context)
        //{
        //    _client.Connected();
        //}

        protected override void ChannelRead0(IChannelHandlerContext context, WebSocketFrame frame)
        {
            if (frame is TextWebSocketFrame textFrame)
            {
                _client.TextMessage(textFrame.Text());
                return;
            }

            if (frame is BinaryWebSocketFrame)
            {
                _client.BinaryMessage(frame.Content.ToBytes());
                return;
            }

            if (frame is CloseWebSocketFrame)
            {
                context.CloseAsync();
                return;
            }
        }

        public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush();

        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            context.CloseAsync();
            _client.Ex(exception);
        }

        public override void ChannelInactive(IChannelHandlerContext context)
        {
            _client.Disconnected();
        }

        public override void UserEventTriggered(IChannelHandlerContext context, object evt)
        {
            if (evt is IdleStateEvent eventState)
            {
                if (eventState != null)
                {
                    context.Channel.CloseAsync();
                }

                return;
            }

            if (evt is WebSocketClientProtocolHandler.ClientHandshakeStateEvent state)
            {
                if (state == WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HandshakeComplete) //握手成功才表示连接成功
                {
                    //_client.Connected();
                    _client._slim2.Release(1);
                }

                return;
            }
        }

    }
}
